/**
 * 
 */
package org.swing.utility.jai.util;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.media.jai.JAI;
/**
 * @author Quynh Nhu
 *
 */
public final class JpegImageWriter {
	  private JpegImageWriter() {
	  }

	  /**
	   * <doc:para>Write the image as a Jpeg to the file specified by the filename.</doc:para>
	   * 
	   * @param image The image to be output
	   * @param file The file to write the jpeg image to
	   */
	  public static void write(final RenderedImage image, final File file)
	    throws IOException {
	    OutputStream out = new FileOutputStream(file);
	    try {
	      write(image, out);
	    } finally {
	      out.flush();
	      out.close();
	    }
	    if (file.length() == 0) {
	      file.delete();
	      throw new FileNotFoundException();
	    }
	  }

	  /**
	   * <doc:para>Write the image as a Jpeg to the output stream.</doc:para>
	   * 
	   * @param image The image to be output
	   * @param out The stream to write the jpeg image to
	   */
	  public static void write(final RenderedImage image, final OutputStream out) {
	    ParameterBlock pb = new ParameterBlock();
	    pb.addSource(image);
	    pb.add(out);
	    pb.add("JPEG");
	    JAI.create("encode", pb);
	  }

	}